package com.erbadagang.springcloudalibaba.stream.rocketmq.producer.message;

import java.security.SecureRandom;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @ClassName
 * @Description
 * @Author liwq
 * @Date 2021/4/13 12:26
 * @Version 1.0
 */
public class IDUtil {
    private static final SecureRandom secureRandomNumberGenerator = new SecureRandom();

    public IDUtil() {
    }

    public static String getSecureRandomId() {
        byte[] randomBytes = new byte[16];
        secureRandomNumberGenerator.nextBytes(randomBytes);
        randomBytes[6] = (byte) (randomBytes[6] & 15);
        randomBytes[6] = (byte) (randomBytes[6] | 64);
        randomBytes[8] = (byte) (randomBytes[8] & 63);
        randomBytes[8] = (byte) (randomBytes[8] | 128);
        long mostSigBits = 0L;
        long leastSigBits = 0L;

        int i;
        for (i = 0; i < 8; ++i) {
            mostSigBits = mostSigBits << 8 | (long) (randomBytes[i] & 255);
        }

        for (i = 8; i < 16; ++i) {
            leastSigBits = leastSigBits << 8 | (long) (randomBytes[i] & 255);
        }

        return digits(mostSigBits >> 32, 8) + digits(mostSigBits >> 16, 4) + digits(mostSigBits, 4) + digits(leastSigBits >> 48, 4) + digits(leastSigBits, 12);
    }

    private static String digits(long val, int digits) {
        long hi = 1L << digits * 4;
        return Long.toHexString(hi | val & hi - 1L).substring(1);
    }

    public static Long getRandomNumber() {
        return ThreadLocalRandom.current().nextLong();
    }

    public static void main(String[] args) {
        String hasCommand = "0";
        String allowApproveOperate = "1";
        String commandResult = "1";

        System.out.println("1".equals(hasCommand));
        System.out.println("1".equals(allowApproveOperate));
        System.out.println("1".equals(commandResult));
    }
}
